<template>
  <view class="category-container">
    <!-- 一级标签 -->
    <scroll-view scroll-x class="level-one-tabs">
      <view 
        v-for="category in topLevelCategories" 
        :key="category.id"
        class="level-one-tab"
        :class="{ active: activeTopLevelId === category.id }"
        @click="handleTopLevelClick(category)"
      >
        <view class="tab-icon">
          <text class="icon">{{ getCategoryIcon(category.name) }}</text>
        </view>
        <text class="tab-name">{{ category.name }}</text>
      </view>
    </scroll-view>

    <!-- 二级标签 -->
    <view class="level-two-section" v-if="activeTopLevel && activeTopLevel.children">
      <scroll-view scroll-x class="level-two-tabs">
        <view 
          v-for="category in activeTopLevel.children" 
          :key="category.id"
          class="level-two-tab"
          :class="{ active: activeSecondLevelId === category.id }"
          @click="handleSecondLevelClick(category)"
        >
          <view class="tab-icon">
            <text class="icon">{{ getCategoryIcon(category.name) }}</text>
          </view>
          <text class="tab-name">{{ category.name }}</text>
        </view>
      </scroll-view>

      <!-- 三级标签 -->
      <view class="level-three-section" v-if="activeSecondLevel && activeSecondLevel.children">
        <view class="level-three-grid">
          <view 
            v-for="category in activeSecondLevel.children" 
            :key="category.id"
            class="level-three-item"
            @click="handleThirdLevelClick(category)"
          >
            <view class="item-icon">
              <text class="icon">{{ getCategoryIcon(category.name) }}</text>
            </view>
            <text class="item-name">{{ category.name }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-state">
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 空状态 -->
    <view v-if="!loading && topLevelCategories.length === 0" class="empty-state">
      <text class="empty-text">暂无分类数据</text>
    </view>
  </view>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useCategoryStore } from '@/store/category'

export default {
  setup() {
    const categoryStore = useCategoryStore()
    
    // 响应式数据
    const activeTopLevelId = ref(1) // 默认选中"支出"
    const activeSecondLevelId = ref(null)
    const loading = ref(false)

    // 计算属性 - 添加安全检查和默认值
    const topLevelCategories = computed(() => {
      return Array.isArray(categoryStore.categoryTree) ? categoryStore.categoryTree : []
    })

    const activeTopLevel = computed(() => {
      if (!Array.isArray(topLevelCategories.value)) return null
      return topLevelCategories.value.find(cat => cat && cat.id === activeTopLevelId.value) || null
    })

    const activeSecondLevel = computed(() => {
      if (!activeTopLevel.value || !activeSecondLevelId.value) return null
      if (!Array.isArray(activeTopLevel.value.children)) return null
      return activeTopLevel.value.children.find(cat => cat && cat.id === activeSecondLevelId.value) || null
    })

    // 方法
    const handleTopLevelClick = (category) => {
      if (!category || !category.id) return
      
      activeTopLevelId.value = category.id
      activeSecondLevelId.value = null
      
      // 如果有子分类，默认选中第一个
      if (category.children && Array.isArray(category.children) && category.children.length > 0) {
        activeSecondLevelId.value = category.children[0].id
      }
    }

    const handleSecondLevelClick = (category) => {
      if (!category || !category.id) return
      activeSecondLevelId.value = category.id
    }

    const handleThirdLevelClick = (category) => {
      console.log('选中三级分类:', category)
      uni.showToast({
        title: `选中: ${category.name}`,
        icon: 'none'
      })
    }

    const getCategoryIcon = (name) => {
      const iconMap = {
        '支出': '💰', '收入': '💵', '转账': '🔄', '借贷': '📝',
        '购物消费': '🛒', '食品餐饮': '🍽️', '出行交通': '🚗', '酒店住宿': '🏨',
        '休闲娱乐': '🎮', '慈善捐款': '❤️', '文化教育': '📚', '健康医疗': '🏥',
        '居家生活': '🏠', '人情往来': '🎁', '早餐': '🌅', '午餐': '🌞', '晚餐': '🌙',
        '宵夜': '🌃', '零食': '🍿', '水果': '🍎', '酒水饮料': '🍹'
      }
      return iconMap[name] || '📁'
    }

    // 加载分类数据
    const loadCategories = async () => {
      loading.value = true
      try {
        await categoryStore.loadCategoryTree()
        
        // 设置默认选中状态
        if (topLevelCategories.value.length > 0) {
          const expenseCategory = topLevelCategories.value.find(cat => cat.name === '支出')
          if (expenseCategory && expenseCategory.children && expenseCategory.children.length > 0) {
            activeTopLevelId.value = expenseCategory.id
            activeSecondLevelId.value = expenseCategory.children[0].id
          }
        }
      } catch (error) {
        console.error('加载分类失败:', error)
        uni.showToast({
          title: '加载分类失败',
          icon: 'none'
        })
      } finally {
        loading.value = false
      }
    }

    // 生命周期
    onMounted(() => {
      loadCategories()
    })

    return {
      // 响应式数据
      activeTopLevelId,
      activeSecondLevelId,
      loading,
      
      // 计算属性
      topLevelCategories,
      activeTopLevel,
      activeSecondLevel,
      
      // 方法
      handleTopLevelClick,
      handleSecondLevelClick,
      handleThirdLevelClick,
      getCategoryIcon
    }
  }
}
</script>

<style scoped>
.category-container {
  background: #f8f9fa;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.level-one-tabs {
  white-space: nowrap;
  background: white;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
}

.level-one-tab {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  padding: 0 30rpx;
  min-width: 120rpx;
}

.level-one-tab.active .tab-icon {
  background: #ff6b6b;
  color: white;
}

.level-one-tab.active .tab-name {
  color: #ff6b6b;
  font-weight: bold;
}

.tab-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10rpx;
  transition: all 0.3s;
}

.tab-icon .icon {
  font-size: 36rpx;
}

.tab-name {
  font-size: 24rpx;
  color: #666;
}

.level-two-section {
  background: white;
  margin: 20rpx;
  border-radius: 16rpx;
  overflow: hidden;
}

.level-two-tabs {
  white-space: nowrap;
  padding: 30rpx 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.level-two-tab {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  padding: 0 25rpx;
  min-width: 100rpx;
}

.level-two-tab.active .tab-icon {
  background: #4ecdc4;
  color: white;
}

.level-two-tab.active .tab-name {
  color: #4ecdc4;
  font-weight: bold;
}

.level-two-tab .tab-icon {
  width: 70rpx;
  height: 70rpx;
}

.level-two-tab .tab-icon .icon {
  font-size: 32rpx;
}

.level-three-section {
  padding: 30rpx 20rpx;
}

.level-three-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 30rpx;
}

.level-three-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.level-three-item .item-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15rpx;
}

.level-three-item .item-icon .icon {
  font-size: 28rpx;
  color: #666;
}

.level-three-item .item-name {
  font-size: 22rpx;
  color: #666;
  text-align: center;
}

.loading-state, .empty-state {
  text-align: center;
  padding: 100rpx 20rpx;
}

.loading-text, .empty-text {
  font-size: 28rpx;
  color: #999;
}
</style>